<template>
  <div ref="chatContentRef" class="chat-content w-full h-full overflow-auto p-12px">
    <template v-for="msgItem in msgList" :key="msgItem.id">
      <component :is="msgComponent[msgItem.type]" :msg-item="msgItem"></component>
    </template>
  </div>
</template>

<script setup>
import { defineAsyncComponent, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';

const props = defineProps({
  msgList: {
    type: Array,
    default: () => [],
  },
});

const msgComponent = {
  MsgCard: defineAsyncComponent(() => import('../messageComponents/MsgCard.vue')),
  MsgB2C: defineAsyncComponent(() => import('../messageComponents/MsgB2C.vue')),
  MsgC2B: defineAsyncComponent(() => import('../messageComponents/MsgC2B.vue')),
  MsgTips: defineAsyncComponent(() => import('../messageComponents/MsgTips.vue')),
};

const chatContentRef = ref(null);

onMounted(() => {
  let unWatchContent = watch(
    () => props.msgList,
    (newV) => {
      newV &&
        nextTick(() => {
          const chatContentEl = chatContentRef.value;
          chatContentEl.scrollTop = chatContentEl.scrollHeight;
        });
    },
    { immediate: true, deep: true },
  );

  onUnmounted(() => unWatchContent?.());
});
</script>

<style scoped lang="scss"></style>
